<template>
  <view class="confirm-order">
    <!-- 当没有选中商品时显示提示信息 -->
    <view v-if="Object.keys(filteredShopCartList).length === 0" class="no-selected-items">
      <text class="no-selected-items-text">购物车中没有选中任何商品</text>
    </view>
    <!-- 收货地址部分 -->
    <view class="address-section" v-if="Object.keys(filteredShopCartList).length > 0">
      <view class="section-title">收货地址</view>
      <view class="address-content">
        <text class="address-text">{{this.currentAddress}}</text>
        <text class="contact-info">{{this.currentName}}   {{this.currentPhone}}</text>
        <text class="contact-info" style="float: right;" @click="gotoAddress">更改</text>
      </view>
    </view>

    <!-- 商品列表部分 -->
    <view class="goods-section" v-if="Object.keys(filteredShopCartList).length > 0">
      <view class="section-title">商品清单</view>
      <view 
        class="shop-group" 
        v-for="(list, shopId) in filteredShopCartList" 
        :key="shopId"
      >
        <view class="shop-title">{{ getShopName(shopId) }}</view>
        <view 
          class="goods-item" 
          v-for="(item, index) in list.items" 
          :key="index"
        >
          <view class="goods-info">
            <text class="goods-name">{{ item.name }}</text>
            <text class="goods-spec">250g/份</text>
          </view>
          <view class="goods-price">
            <text class="price">¥{{ item.price.toFixed(2) }} x {{ item.count }}</text>
            <text class="total">¥{{ (item.price * item.count).toFixed(2) }}</text>
          </view>
        </view>
      </view>
    </view>
    <view class="cart-empty" v-else>
  <text class="cart-empty-text">没有选中的商品</text>
</view>

    <!-- 底部汇总 -->
    <view class="footer" v-if="Object.keys(filteredShopCartList).length > 0">
      <text class="total-price">实付金额：¥{{ selectedTotalPrice }}</text>
      <button @click="gotoOrder()">提交订单</button>
    </view>
  </view>
</template>

<script>
<<<<<<< HEAD
	import config from '../../config';
	
	export default {
	  data() {
	    return {
	      cartList: [],
	      shopList: [],
	      shopCartList: {},
	      currentAddress: "",
	      currentName: "",
	      currentPhone: ""
	    };
	  },
	  computed: {
	    // 过滤只显示选中的商品
	    filteredShopCartList() {
	      const filtered = {};
	      Object.keys(this.shopCartList).forEach(shopId => {
	        const items = this.shopCartList[shopId].items.filter(item => item.selected);
	        if (items.length > 0) {
	          filtered[shopId] = {
	           ...this.shopCartList[shopId],
	            items: items
	          };
	        }
	      });
	      return filtered;
	    },
	    selectedTotalPrice() {
	      let total = 0;
	      Object.values(this.filteredShopCartList).forEach(shop => {
	        shop.items.forEach(item => {
	          total += item.price * item.count;
	        });
	      });
	      return total.toFixed(2);
	    }
	  },
	  methods: {
	    gotoAddress() {
	      uni.navigateTo({
	        url: `/pages/changeAddress/index`
	      });
	    },
	    getShopName(shopId) {
	      uni.request({
	        url: config.URL + "/shop",
	        method: 'GET',
	        success: (res) => {
	          this.shopList = res.data;
	          const shop = this.shopList.find(shop => shop._id === shopId);
	          console.log(shop);
	          return shop? shop.name : '未知超市';
	        },
	        fail: (error) => {
	          console.error('获取店铺数据失败:', error);
	        }
	      });
	    },
	    // 获取购物车数据
	 async fetchCartData() {
	     return new Promise((resolve, reject) => {
	         uni.request({
	             url: config.URL + "/cart",
	             method: 'GET',
	             data: { userId: uni.getStorageSync('ID') },
	             success: (res) => {
	                 console.log('获取的购物车数据:', res.data);
	                 this.cartList = res.data;
	                 this.classifyCartItems();
	                 resolve();
	             },
	             fail: (error) => {
	                 console.error('获取购物车数据失败:', error);
	                 reject(error);
	             }
	         });
	     });
	 },
	    // 分类商品
	   classifyCartItems() {
	     const classified = {};
	     this.cartList.forEach(item => {
	       // 明确检查 selected 是否为 true
	       if (item.selected !== true) {
	         console.warn("Item is not selected:", item);
	         return;
	       }
	       const shopId = item.shopId;
	       if (!shopId) {
	         console.error("Item has no shopId:", item);
	         return;
	       }
	       if (!classified[shopId]) {
	         classified[shopId] = { shopId, items: [] };
	       }
	       classified[shopId].items.push(item);
	     });
	     // 使用响应式赋值（替换整个对象）
	     this.shopCartList = { ...classified };
	   },
	    gotoOrder() {
	      uni.showModal({
	        title: '确认订单',
	        content: '您确定要提交订单吗？',
	        success: (res) => {
	          if (res.confirm) {
	            const promises = this.cartList.map(item => {
	              return new Promise((resolve, reject) => {
	                uni.request({
	                  url: config.URL + "/orders",
	                  method: 'POST',
	                  data: {
	                    userId: uni.getStorageSync('ID'),
	                    shopId: item.shopId,
	                    items: [item],
	                  },
	                  success: (res) => {
	                    console.log("添加成功 ");
	                    resolve();
	                  },
	                  fail: (error) => {
	                    console.error('提交订单失败:', error);
	                    reject(error);
	                  }
	                });
	              });
	            });
	
	            Promise.all(promises).then(() => {
	              uni.navigateTo({
	                url: `/pages/pay/index`
	              });
	              window.location.reload();
	            });
	          }
	        }
	      });
	    }
	  },

	async onShow() {
	    if (this.cartList.length === 0) {
	        try {
	            await this.fetchCartData();
	        } catch (error) {
	            console.error('获取购物车数据失败:', error);
	        }
	    }
	    uni.request({
	        url: config.URL + "/address",
	        method: 'GET',
	        success: (res) => {
	            let addresses = [...res.data];
	            if (addresses.length >= 2) {
	                [addresses[0], addresses[1]] = [addresses[1], addresses[0]];
	            }
	            // 检查并设置默认值
	            this.currentAddress = uni.getStorageSync('address') || '请设置收货地址';
	            this.currentName = uni.getStorageSync('name') || '匿名';
	            this.currentPhone = uni.getStorageSync('phone') || '未设置';
	        },
	        fail: (error) => {
	            console.error('地址获取失败:', error);
	        }
	    });
	},
	onLoad(option) {
	    console.log('onLoad 方法执行，option:', option);
	    if (option.selectedItems) {
	        const selectedItems = JSON.parse(decodeURIComponent(option.selectedItems));
	        // 将所有商品的 selected 属性设置为 true
	        const allSelectedItems = selectedItems.map(item => ({...item, selected: true }));
	        this.cartList = allSelectedItems;
	        this.classifyCartItems();
	    }
	}
	};
=======
import axios from 'axios';

export default {
  data() {
    return {
      cartList: [],
      shopList: [],
      shopCartList: {},
      currentAddress:"",
      currentName:"",
      currentPhone:""
    };
  },
  computed: {
    // 过滤只显示选中的商品
    filteredShopCartList() {
      const filtered = {};
      Object.keys(this.shopCartList).forEach(shopId => {
        const items = this.shopCartList[shopId].items.filter(item => item.selected);
        if (items.length > 0) {
          filtered[shopId] = {
           ...this.shopCartList[shopId],
            items: items
          };
        }
      });
      return filtered;
    },
    selectedTotalPrice() {
      let total = 0;
      Object.values(this.filteredShopCartList).forEach(shop => {
        shop.items.forEach(item => {
          total += item.price * item.count;
        });
      });
      return total.toFixed(2);
    }
  },
  methods: {
    gotoAddress(){
      uni.navigateTo({
        url: `/pages/changeAddress/index`
      });
    },
    getShopName(shopId) {
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/shop").then(res=>{
        this.shopList=res.data
      })
      const shop = this.shopList.find(shop => shop._id === shopId);
      console.log(shop)
      return shop? shop.name : '未知超市';
    },
    // 获取购物车数据
    fetchCartData() {
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", {
        params: { userId: uni.getStorageSync('ID') }
      })
     .then(res => {
        this.classifyCartItems();
        console.log(this.cartList);
      })
     .catch(error => {
        console.error('获取购物车数据失败:', error);
      });
    },
    // 分类商品
    classifyCartItems() {
      const classified = {};
      this.cartList.forEach(item => {
        if (!item.selected) return;
        const shopId = item.shopId;
        if (!classified[shopId]) {
          classified[shopId] = {
            shopId: shopId,
            items: []
          };
        }
        classified[shopId].items.push(item);
      });
      this.shopCartList = classified;
    },
    gotoOrder() {
  uni.showModal({
    title: '确认订单',
    content: '您确定要提交订单吗？',
    success: (res) => {
      if (res.confirm) {
        this.cartList.forEach(item=>{
           axios.post("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/orders",{
              userId: uni.getStorageSync('ID'),
              shopId: item.shopId,
              items: [item],
           }).then(res=>{
            console.log("添加成功 ");
           })
        })
       
 
         uni.navigateTo({
          url: `/pages/pay/index`
        });
        window.location.reload();
        
        
        
      }
    }
  });
}
  },
  onShow() {
    this.fetchCartData();
   axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address").then(res => {
   
    let addresses = [...res.data];
 
    if (addresses.length >= 2) {
      [addresses[0], addresses[1]] = [addresses[1], addresses[0]];
    }

    this.currentAddress = uni.getStorageSync('address') 
    this.currentName = uni.getStorageSync('name') 
    this.currentPhone = uni.getStorageSync('phone') 
  }).catch(error => {
    console.error('地址获取失败:', error);
  });
 
    
  },
  onLoad(option) {
  if (option.selectedItems) {
    const selectedItems = JSON.parse(decodeURIComponent(option.selectedItems));
    this.cartList = selectedItems;
    this.classifyCartItems();
  } else {
    this.cartList = [];
    this.classifyCartItems();
  }
},

};
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
</script>

<style scoped>
/* 订单详情页 style 部分 */
.cart-empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 16px;
}
.confirm-order {
  padding: 20rpx;
  background: #f5f5f5;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding: 15rpx 0;
  border-bottom: 1px solid #eee;
}

.address-section {
  background: white;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.address-content {
  padding: 15rpx 0;
}

.address-text {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 10rpx;
}

.contact-info {
  font-size: 14px;
  color: #666;
}

.goods-section {
  background: white;
  padding: 20rpx;
  border-radius: 8rpx;
}

.shop-title {
  font-size: 16px;
  color: #333;
  padding: 15rpx 0;
  border-bottom: 1px dashed #eee;
}

.goods-item {
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.goods-info {
  margin-bottom: 10rpx;
}

.goods-name {
  font-size: 15px;
  color: #333;
  margin-right: 15rpx;
}

.goods-spec {
  font-size: 12px;
  color: #999;
}

.goods-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 14px;
  color: #666;
}

.total {
  font-size: 15px;
  color: #f60;

}

.footer {
  /* position: fixed;
  bottom: 0; */
  width: 100%;
  height: 100rpx;
  background: white;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-right: 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}
.footer button {
  background-color: #007aff;
  margin-left: 100px;
}

.total-price {
  font-size: 18px;
  color: #f60;
  font-weight: bold;
}

.no-selected-items {
  text-align: center;
  padding: 50rpx 0;
  font-size: 16px;
  color: #666;
}

.no-selected-items-text {
  color: #666;
}
</style>